package thread;


import java.util.PriorityQueue;


class MyTimertask implements Comparable<MyTimertask>{
    private long time;
    private Runnable runnable;


    public MyTimertask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }

    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimertask o) {
        return (int) (this.time-o.time);
    }
}


class MyTimer{
    private Thread t=null;
    private PriorityQueue<MyTimertask> queue=new PriorityQueue<>();
    private Object locker=new Object();

    public void schedule(Runnable runnable,long delay){
        MyTimertask task=new MyTimertask(runnable,delay);
        queue.offer(task);
        locker.notify();
    }

    public MyTimer(){
        t=new Thread(()->{
           synchronized (locker){
              try{
                  while (true){
                      while (queue.isEmpty()){
                          locker.wait();
                      }
                      MyTimertask task=queue.peek();
                      long curTime=System.currentTimeMillis();
                      if (curTime>=task.getTime()){
                          queue.poll();
                          task.run();
                      }else {
                          continue;
                      }
                  }
              }catch (InterruptedException e){
                  e.printStackTrace();
              }
           }
        });

        t.start();
    }
}



public class ThreadDemo27 {

}